package com.csdj.file;

import java.io.*;

public class FileTest {

    public static void main(String[] args) {
        copy("e:/test/test.txt","d:/kkk.txt");
    }

    public static void  readFile(){
        try {
            FileInputStream fis = new FileInputStream("e:/test/test.txt");
            if(fis.available()>0){
                int read;
                while((read = fis.read()) != -1){
                    System.out.print((char)read);
                }
            }
            fis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void readArrayByte()  {
        try {
            FileInputStream fis = new FileInputStream("e:/test/aaa.txt");
            byte[] data = new byte[1024];
            if(fis.available()>0){
                fis.read(data);
                System.out.println(new String(data));
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void outputFile(){
        try {
            File file = new File("e:/test/aaa.txt");
            //判断文件存在， 如果不存在则新建一个
            if(!file.exists()){
                file.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(file,true);
            String str = "i am a chinese";
            byte[] b = str.getBytes();
            fos.write(b);
            fos.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void copy(String src,String dest){
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
             fis = new FileInputStream(src);
             fos = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            if(fis.available()>0){
                while(fis.read(buf) != -1){
                    fos.write(buf);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if(fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}
